package org.lex.checksum.core;

import java.util.zip.Adler32;
import java.util.zip.CRC32;
import java.util.zip.Checksum;

public class ChecksumAlgorithm implements Algorithm {
	private final String algorithm;
	private Checksum checksum = null;

	public ChecksumAlgorithm(String algorithm) {
		this.algorithm = algorithm;
		if (AlgorithmService.CHECKSUM_ADLER32.equalsIgnoreCase(algorithm)) {
			this.checksum = new Adler32();
		} else if (AlgorithmService.CHECKSUM_CRC32.equalsIgnoreCase(algorithm)) {
			this.checksum = new CRC32();
		} else {
			throw new IllegalArgumentException();
		}
	}

	public void reset() {
		this.checksum.reset();
	}

	public String finish() {
		return Long.toHexString(this.checksum.getValue());
	}

	public void update(byte[] b, int offset, int len) {
		checksum.update(b, offset, len);
	}

	@Override
	public ChecksumAlgorithm clone() {
		return new ChecksumAlgorithm(this.algorithm);
	}
}
